<template>
<label :class="[$style.container]" tabindex="0">
  <el-tag size="small" effect="plain" type="primary" closable v-for="row in value" :key="row" class="mx-1" @close="onRemove(row)">{{row}}</el-tag>
  <input type="text"
    :hidden="exceed"
    v-model="text" :size="text.length + 4"
    maxlength="10" :class="[$style.input]" tabindex="-1" ref="inputEle" @keyup.enter="onAdd" @keyup.188="onAdd">
    <div v-if="value.length < 1 && !text" :class="[$style.placeholder]" >使用回车或,来添加一个标签</div>
</label>
</template>

<script lang="ts">

import { Vue, Component, Prop, Emit, Inject, Ref } from 'vue-property-decorator'

@Component
export default class TagInput extends Vue {
  @Ref() inputEle!: HTMLInputElement

  @Prop(Array) value!: string[]

  @Prop({ type: Number, default: 3 }) limit!: number

  @Emit() input (value: string[]) {}

  text = ''

  get exceed () {
    return this.value.length >= this.limit
  }

  onAdd () {
    const t = this.text.replaceAll(',', '')
    if (!t) return
    if (this.value.some(v => v === t)) return
    this.input([...this.value, t])
    this.text = ''
  }

  onRemove (row: string) {
    const n = this.value.filter(v => v !== row)
    this.input(n)
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {
  display: inline-block;
  position: relative;
  width: 100%;
  min-height: 32px;
  border: 1px solid $border-color;
  border-radius: 2px;
  transition: all .35s ease;

  &:hover {
    border-color: $text-placeholder-color;
    outline: 0;
  }

  &:focus, &:active {
    border-color: $color-primary;
    outline: 0;
  }

}

.input {
  min-width: 24px;
  max-width: calc(100% - 24px);
  border: none;
  outline: 0;
  &:focus, &:active {
    outline: 0;
  }
}

.placeholder {
  position: absolute;
  color: $text-placeholder-color;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  width: 100%;
  padding: 0 12px;;
}
</style>
